package com.canal.display.handler;

import com.canal.display.response.Result;
import com.canal.display.response.ResultUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.www.NonceExpiredException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Administrator
 * @description
 * @date 2019年03月17 13:33
 */
public class TokenFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
            throws IOException, ServletException {
        ObjectMapper mapper = new ObjectMapper();
        Result result = new Result();
        if (e instanceof NonceExpiredException || e instanceof InternalAuthenticationServiceException) {
            result = ResultUtil.makeFailure("令牌已失效!");
        } else if(e instanceof InsufficientAuthenticationException) {
            result = ResultUtil.makeFailure("令牌不存在!");
        }
        String jsonResult = mapper.writeValueAsString(result);
        response.setContentType("application/json;charset=utf8");
        PrintWriter writer = response.getWriter();
        writer.write(jsonResult);
        writer.flush();
        writer.close();
    }
}
